package com.yunlongn.common.json.jackson.deserializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.yunlongn.common.json.jackson.factory.AbstractJsonDeserializer;
import com.yunlongn.common.json.util.DateFormatUtils;
import com.yunlongn.common.json.util.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * LocalDateTime反序列化
 * @author Yun
 * @since 20210902
 */
public class LocalDateTimeDeserializer extends AbstractJsonDeserializer<LocalDateTime> {

    private int zone;

    public LocalDateTimeDeserializer() {
        this.zone = 8;
    }

    public LocalDateTimeDeserializer(int zone) {
        this.zone = zone;
    }

    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String datetime = jsonParser.getText();
        if (StringUtils.isNumber(datetime)) {
            long times = Long.parseLong(datetime);
            if (datetime.length() == 13) {
                times /= 1000;
            }
            return LocalDateTime.ofEpochSecond(times, 0, ZoneOffset.ofHours(zone));
        } else {
            DateTimeFormatter formatter = DateFormatUtils.chooseDateTimeFormatter(datetime);
            return LocalDateTime.parse(datetime, formatter);
        }
    }

}